package fire.and.near.challenger;

import java.util.List;

import com.facebook.Response;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.ImageButton;
import android.widget.Toast;
import fire.and.near.challenger.database.ChallengeModel;
import fire.and.near.challenger.database.ChallengeStatus;
import fire.and.near.challenger.database.DatabaseActivity;
import fire.and.near.challenger.database.DatabaseAsyncTask;
import fire.and.near.challenger.database.DatabaseResponse;
import fire.and.near.challenger.database.ChallengeModel.ChallengeType;
import fire.and.near.challenger.database.DatabaseAsyncTask.DatabaseQueryOptions;
import fire.and.near.challenger.facebook.FacebookActionAdapter;
import fire.and.near.challenger.facebook.FacebookHelper;
import fire.and.near.challenger.facebook.MessageBuilder;
import fire.and.near.challenger.facebook.MessageType;
import fire.and.near.challenger.util.Consts;
import fire.and.near.challenger.web.HttpRequestSender;

public class PendingChallengesListAdapter extends ArrayAdapter<ChallengeModel> implements DatabaseActivity {
	
	private static int _queuedActions = 0;
	private static Object _lock = new Object();
	private Context context;
	private ArrayAdapter<ChallengeModel> mThisAdapter;
	private FacebookHelper mFbHelper = LoginActivity.mFbHelper;
	
	public PendingChallengesListAdapter(Context context, int resource) {
		super(context, resource);
		
		this.context = context;
		this.mThisAdapter = this;
	}

	public PendingChallengesListAdapter(Context context, int resource,
			List<ChallengeModel> objects) {
		super(context, resource, objects);
		
		this.context = context;
		this.mThisAdapter = this;
	}
	
	@Override
	public View getView(int position, View convertedView, ViewGroup parent) {
		View v = convertedView;

		if (v == null) {
			LayoutInflater inflater = ((Activity) this.getContext())
					.getLayoutInflater();
			v = inflater.inflate(R.layout.pending_challenges_list_row, null);
		}

		ChallengeModel challenge = getItem(position);

		Log.i("PENDING_FB", "getView");
		
		if (challenge != null) {
			Log.i("PENDING_FB", "challenge not null");
			TextView tvDesc = (TextView) v.findViewById(R.id.textView_pend_desc);
			tvDesc.setText(challenge.getDescription() == null ? challenge.getAnswer() : challenge.getDescription());
			
			String name = null;
			
			if (challenge.getChallenger().getName() != null) {
				name = challenge.getChallenger().getName();
			} else if(challenge.getChallengedID() == challenge.getChallenger().getFbID()) {
				name = Consts.ME;
			} else {
				name = Consts.COMPANY_NAME;
			}
			
			((TextView) v.findViewById(R.id.textView_pend_name)).setText(name);
			
			
			if (challenge.getStatus() == ChallengeStatus.IN_HISTORY) {
				if (challenge.isAccepted()) {
					
					if (challenge.getChallengeType() == ChallengeType.TEXT) {
						setTextboxIcon(tvDesc, v, R.drawable.text_success);
					} else {
						setTextboxIcon(tvDesc, v, R.drawable.photo_success);
					}
				} else {
					if (challenge.getChallengeType() == ChallengeType.TEXT) {
						setTextboxIcon(tvDesc, v, R.drawable.text_fail);
					} else {
						setTextboxIcon(tvDesc, v, R.drawable.photo_fail);
					}
				}
			} else {
				if (challenge.getChallengeType() == ChallengeType.PHOTO) {
					setTextboxIcon(tvDesc, v, R.drawable.photo);
				} else {
					setTextboxIcon(tvDesc, v, R.drawable.text);
				}
			}
			
			((ImageButton) v.findViewById(R.id.btnShare))
					.setOnClickListener(new ShareActionListener(challenge));
			
			((ImageButton) v.findViewById(R.id.btnDelete))
					.setOnClickListener(new DeleteActionListener(challenge));
		} else {
			Log.i("PENDING_FB", "challenge null");
		}

		return v;
	}
	
	private void setTextboxIcon(TextView target, View parent, int resId) {
		target.setCompoundDrawablesWithIntrinsicBounds(parent.getResources()
								.getDrawable(resId), 
								null, 
								null, 
								null);
	}
	
	private class ShareActionListener implements View.OnClickListener {

		private ChallengeModel _model;
		
		public ShareActionListener(ChallengeModel model) {
			_model = model;
		}
		
		@Override
		public void onClick(View v) {
			Log.i("PENDING_FB", "onClick");
			
			synchronized (_lock) {
				_queuedActions++;
				Log.i("QUEUED_WORK", "FB_START " + _queuedActions);
			}
			
			if (HttpRequestSender.isNetworkAvailable((Activity)context)) {
				Bitmap bitmap = null;
				
				mThisAdapter.remove(_model);
				mThisAdapter.notifyDataSetChanged();
				
				if (_model.getPhotoPath() != null) {
					bitmap = BitmapFactory.decodeFile(_model.getPhotoPath());
				}
				
				MessageBuilder msgBuilder = 
						new MessageBuilder(	_model.getDescription(), 
											_model.getAnswer(), 
											_model.getHashtag(), 
											(_model.getChallenger().getFbID() == _model.getChallengedID()) 
													? MessageType.SelfChallenge 
													: MessageType.CompleteChallenge);
				
				mFbHelper.postStatusUpdate(	(Activity)context, 
											msgBuilder.build(), 
											"" + _model.getChallenger().getFbID(), 
											bitmap, 
											new FacebookActionAdapter() {
												@Override
												public void onActionCompleted(
														Response response) {
													
													if (response.getError() == null) {
														
														synchronized (_lock) {
															_queuedActions++;

															Log.i("QUEUED_WORK", "FB_END, DB_Start " + _queuedActions);
														}
														
														Toast.makeText(context, "Posted on Facebook!", Toast.LENGTH_SHORT).show();
														
														new DatabaseAsyncTask(context, DatabaseQueryOptions.COMPLETE).execute(_model.getID());
														Log.i("SHAREBTN", "shared");
														
													} else {
														Log.e("SHAREBTN", response.getError().toString());
													}
													
													synchronized (_lock) {
														if (_queuedActions > 0) {
															_queuedActions--;
														}
														Log.i("QUEUED_WORK", "FB_END " + _queuedActions);
													}
												}
											}
				);
			} else {
				HttpRequestSender.connectingToServerErrorMessage((Activity)context);
			}
		}
	}
	
	private class DeleteActionListener implements View.OnClickListener {

		private ChallengeModel _model;
		
		public DeleteActionListener(ChallengeModel model) {
			_model = model;
		}
		
		@Override
		public void onClick(View v) {
			
			synchronized (_lock) {
				_queuedActions++;

				Log.i("QUEUED_WORK", "DB_START " + _queuedActions);
			}
			
			new DatabaseAsyncTask(context, DatabaseQueryOptions.COMPLETE).execute(_model.getID());
			Log.i("DELBTN", "deleted");
			mThisAdapter.remove(_model);
			mThisAdapter.notifyDataSetChanged();
		}
		
	}

	@Override
	public void processDatabaseResponse(DatabaseResponse result) {
		if (result.isSuccessful()) {
			switch (result.getOption()) {
			case COMPLETE:
//				Doesn't work, the activity handles the response, not the adapter
				
//				synchronized (_lock) {
//					_queuedActions--;
//
//					Log.i("QUEUED_WORK", "DB_END " + _queuedActions);
//				}
				break;

			default:
				break;
			}
		}
	}

	@Override
	public void setDatabaseWorking(boolean working) {
		// TODO Auto-generated method stub
		
	}
	
	public synchronized boolean isWorkInProgress() {
		Log.i("QUEUED_WORK", "DB_END " + _queuedActions);
		return _queuedActions != 0;
	}
	
	public synchronized void decreaseActionsCount() {
		if (_queuedActions > 0) {
			_queuedActions--;
		}
	}
}
